package com.sign.common.util.threadpool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author 513422479@qq.com
 * Date on 2020/5/21  21:16
 */
public class NamedThreadFactory implements ThreadFactory {

    private  final AtomicLong atomicLong = new AtomicLong(0);

    private final String threadNamePrefix;

    private final  int priority;

    public NamedThreadFactory(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
        this.priority = Thread.NORM_PRIORITY;
    }

    public NamedThreadFactory(String threadNamePrefix, int priority) {
        this.threadNamePrefix = threadNamePrefix;
        if(priority<= Thread.MAX_PRIORITY && priority >= Thread.MIN_PRIORITY){
            this.priority =priority;
        }
        else{
            this.priority = Thread.NORM_PRIORITY;
        }
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setPriority(priority);
        thread.setName(threadNamePrefix+"-"+atomicLong.incrementAndGet());
        thread.setUncaughtExceptionHandler((t,e) ->{
            {
                System.out.println("THread running faild.Caught exception"+e);
                // 默认的UncaughtExceptionHandler
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t,e);
            }
        });
        return thread;
    }
}
